<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">在当前分类下查询</el-button>
        <el-button @click="getDataList(true)">查询所有分类</el-button>

        <el-button v-if="isAuth('pms:attr:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('pms:attr:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      :highlight-current-row="true"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="40">
      </el-table-column>
      <el-table-column
        prop="attrId"
        header-align="center"
        align="center"
        width="50"
        label="属性id">
      </el-table-column>
      <el-table-column
        prop="attrName"
        header-align="center"
        align="center"
        label="属性名">
      </el-table-column>
      <el-table-column
        prop="searchType"
        header-align="center"
        align="center"
        label="是否需要检索">
        <template slot-scope="slot">
          <el-switch
            v-model="slot.row.searchType"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="icon"
        header-align="center"
        align="center"
        label="属性图标">

        <template slot-scope="slot">
          <img
            style="width: 100px;"
            v-if="hostPrefix"
            :src="hostPrefix+slot.row.icon">
        </template>

      </el-table-column>
      <el-table-column
        prop="valueSelect"
        header-align="center"
        align="center"
        label="可选值列表">
        <template slot-scope="slot">
<!--                      v-for="tag in slot.row.valueSelect.split(',').filter((v,index)=>{return index<3})"
-->
          <el-tag
            :key="tag"
            v-for="(tag,index) in slot.row.valueSelect.split(',')"
            v-if="index<3"
            :disable-transitions="false">
            {{ tag }}
          </el-tag>
        </template>

      </el-table-column>
      <el-table-column
        prop="attrType"
        header-align="center"
        align="center"
        label="属性类型">
        <!--        [0-销售属性，1-基本属性，2-既是销售属性又是基本属性]-->
        <template slot-scope="slot">

          <el-tag v-if="slot.row.attrType===0">销售属性</el-tag>
          <el-tag v-if="slot.row.attrType===1" type="success">基本属性</el-tag>
          <el-tag v-if="slot.row.attrType===2" type="warning">既是销售属性又是基本属性</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="enable"
        header-align="center"
        align="center"
        label="启用状态">
        <!--        [0 - 禁用，1 - 启用]-->
        <template slot-scope="slot">
          <el-switch
            v-model="slot.row.enable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            disabled
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>


      <el-table-column
        prop="categoryName"
        header-align="center"
        align="center"
        label="所属分类">
        <template slot-scope="slot">
          <el-tag v-text="slot.row.categoryName" v-if="slot.row.categoryName"></el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="attrGroupName"
        header-align="center"
        align="center"
        v-if="attrType===1"
        label="所属分组">
        <template slot-scope="slot">
          <el-tag v-text="slot.row.attrGroupName" v-if="slot.row.attrGroupName"></el-tag>
        </template>
      </el-table-column>


      <el-table-column
        prop="showDesc"
        header-align="center"
        align="center"
        label="快速展示">
        <!--        【是否展示在介绍上；0-否 1-是】，在sku中仍然可以调整-->
        <template slot-scope="slot">
          <el-switch
            v-model="slot.row.showDesc"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            disabled
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="associateGroupHandle(scope.row)"
                     v-if="attrType===1">关联分组
          </el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.attrId)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.attrId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"
                   :attrTypeGlobal="attrType"></add-or-update>
    <!--    关联分组-->
    <associate-group-component ref="associateGroupRef"
                               :attrIdGlobal="currentEditingAttrId"
                               @update-attr-list="getDataList"
    ></associate-group-component>
  </div>
</template>

<script>
import AddOrUpdate from './attr-add-or-update'
import uploadToAiliOss from '../../../../api/uploadToAiliOss'
import baseAttrApi from '../../../../api/product/baseAttrApi'
import associateGroupComponent from './associateGroupComponent'

export default {
  props: ['hub', 'attrTypeGlobal'],
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      hostPrefix: '',
      hubLocal: null,
      queryCondition: {
        attrId: null,
        attrName: null,  // 除了属性名，其余的都是数字
        attrType: null,
        catelogId: null,
        enable: null,
        // "icon": "string",
        searchType: null,
        showDesc: null,
        // "valueSelect": "string"}
      },
      // 当前正在编辑的attr
      currentEditingAttrId: null,
      attrType: null
    }
  },
  components: {
    AddOrUpdate, associateGroupComponent
  }
  ,
  activated () {

  }
  ,
  created () {
    this.getHost()

  }
  ,
  mounted () {

  }
  ,
  methods: {
    // 获取数据列表
    getDataList (global) {
      this.dataListLoading = true

      let key = this.dataForm.key

      //console.log(key=="")

      if (/^[0-9]+$/.test(key)) {
        this.queryCondition.attrId = key
      } else if (key.length > 0) {
        this.queryCondition.attrName = key
      }

      if (key == '') {
        this.queryCondition.attrId = null
        this.queryCondition.attrName = null
      }

      // console.log("发送请求")
      baseAttrApi.queryBaseAttrByCondition(this.pageIndex, this.pageSize, {
        catelogId: global ? null : this.queryCondition.catelogId,
        attrName: /*global ? null :*/ this.queryCondition.attrName,
        attrId: /*global ? null :*/ this.queryCondition.attrId,
        attrType: this.attrType, // 这里只查询基本属性
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list

          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false

        /*this.dataList.forEach((attr, index) => {
          categoryApi.getCategoryInfoByCategoryId(attr.catelogId).then(({data}) => {
            this.dataList[index].categoryName = data.category.name
          })
        })*/
      })
    }
    ,
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    }
    ,
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    }
    ,
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    }
    ,
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
        /**
         * 爷组件不能将值传递给孙组件，所以在这里传
         * */
        this.$refs.addOrUpdate.dataForm.attrType = this.attrType

        this.$refs.addOrUpdate.attrType = this.attrType
      })
    }
    ,
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.attrId
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/pms/attr/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
    ,

    /*async*/
    getCategory (row) {

      console.log(row)

      //row.categoryName = 'hello'

      return row.categoryName

      // let p = await categoryApi.getCategoryInfoByCategoryId(categoryId)
      //
      //
      //
      // return p.data.category.name
      //console.log(p)
    }
    ,

    async getHost () {
      let p = await uploadToAiliOss.getHostAddress()
      this.hostPrefix = p.data.host + '/'
      //console.log(p.data)
    },

    associateGroupHandle (row) {
      this.$refs.associateGroupRef.dialogVisible = true
      //this.currentEditingAttrId = row.attrId; // 监听器实现，有bug

      this.$nextTick(() => {
        this.$refs.associateGroupRef.attrIdGlobalHandler(row.attrId)
      })

      //console.log("传递给子组件的数据是",this.currentEditingAttrGroup);
    }
  }
  ,
  watch: {
    hub (val) {
      if (val) {
        this.hubLocal = val

        this.hubLocal.$on('change-category-id', (data, node, nodeSelf) => {
          console.log('attr兄弟组件收到', data, node, nodeSelf)
          if (node.level === 3) {

            this.queryCondition.catelogId = data.catId
            this.getDataList()
          }
        })
      }
    },
    attrTypeGlobal (val) {
      // console.log('attrTypeGlobal 更新了', val)
      if (val === 0 || val === 1 || val === 2) {
        this.attrType = val
      }
      this.getDataList()
    }
  }
}
</script>
